<template>
    <div class="breadcrumb">
        <el-breadcrumb>
            <el-breadcrumb-item v-for="item in crumbArr" :key="item.index" :to="{ path: item.routePath }">
                {{ item.name }}
            </el-breadcrumb-item>
        </el-breadcrumb>
    </div>
</template>

<script setup lang='ts'>
import { layoutData } from "@/pages/managementPage/layout/index"
import { ref, onMounted, watch } from 'vue'
import { useRoute } from "vue-router";
const crumbArr = ref<any>([])
const route = useRoute();
// 解析函数
const parseData = (data, result = []) => {
    for (const item of data) {
        result.push(item);
        if (item.child) {
            parseData(item.child, result);
        }
    }
    return result;
}
// 筛选函数
const filterData = (data, query) => {
    return data.filter(item => {
        // 判断当前项的 routePath 是否包含查询的子字符串
        return item.routePath && item.routePath == query;
    });
}
// 定义转换函数
function parseDataArray(dataString) {
    const dataArray = dataString.split(",");
    return dataArray.map(item => {
        const parts = item.split("-"); // 根据 "-" 分割字符串
        return {
            name: parts[0], // 第一部分是名称
            routePath: parts[1] ? parts[1] : null // 第二部分是路由路径，如果不存在则为 null
        };
    });
}

//home-details 字符串处理格式 home
const processingFormattingStr = () => {
    const routeName = route && typeof route.name === 'string' ? route.name : "";
    if (routeName.includes("-")) {
        const parts = routeName.split("-"); // 将字符串拆分成数组
        return "/" + parts.join("/"); // 将数组元素连接成路径字符串
    } else {
        return `/${routeName}`;
    }
}
const init = () => {
    try {
        // 递归把所有的child转换为一个数组
        const unfoldArr = parseData(layoutData);
        // 哪到当前的页面的路由
        let routePath = processingFormattingStr()
        // console.log(unfoldArr, routePath)
        // 匹配所有数组于当前路由当匹配到拿到当前的item
        const currentMatchOnj = filterData(unfoldArr, routePath)[0];
        // 拿当前对象的breadcrumb数据项
        crumbArr.value = currentMatchOnj && parseDataArray(currentMatchOnj.breadcrumb)
    } catch (error) {
        console.log(error)
    }

}
watch(route, () => {
    init()
});
onMounted(() => {
    init()
})
</script>

<style lang='scss' scoped>
.breadcrumb {
    width: 100%;
    height: 100%;
    display: flex;
    background-color: $white;
    border-radius: 5px;
    align-items: center;
    margin-left: 10px;
}

.el-breadcrumb {
    margin: 0px 10px;
}

// Your scoped styles here
</style>